package com.sinodata.bsm.cicp.collector.oracle;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.mysql.MySQLUtil;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;

/**
 *
 * <p>
 * Description: Oracle 采集器的工具类
 * </p>
 *
 * @author Chao.Liu
 * @version 3.1

 * <p>
 * History:
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2011-11-10 上午11:04:39          Chao.Liu        3.1         To create
 * </p>
 *
 * @since
 * @see
 */
public class OracleCollectorUtil {
    private static Logger logger = Logger.getLogger(MySQLUtil.class);
    public final static String VERSION = "select VERSION  from V$INSTANCE";

    private OracleCollectorUtil() {
    }

    public static Integer getVersion(String db, String ip, String dbName) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String version = "9";
        try {
            conn = DBConnectionUtil.getInstance().getConnection(db, ip, dbName);
            stmt = conn.createStatement();
            rs = stmt.executeQuery(VERSION);

            if (rs.next()) {
                version = rs.getString(1);
            } else {
                logger.info("Oracle Version Not Find.");
            }
        } catch (Exception ex) {
            logger.error("Failed to get the major version of Oracle!", ex);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
            DBConnectionUtil.getInstance().returnConnection(conn);
        }

        version = getMainVersion(version);

        return new Integer(version);
    }

    private static String getMainVersion(String version) {
        logger.info("Oracle Version: " + version);
        String mainVersion = "9";

        Pattern p = Pattern.compile("([\\d]{0,})\\.");
        Matcher m = p.matcher(version);

        if (m.find()) {
            mainVersion = m.group(1);
        }

        return mainVersion;
    }

    public static void main(String[] args) {
        String version = "ort stg 11.22.432 TG";

        Pattern p = Pattern.compile("([\\d]{0,})\\.");
        Matcher m = p.matcher(version);

        if (m.find()) {
            System.out.println("Oracle Version: " + m.group(1));
        }
    }
}
